package com.boot.aop.aspect;

import com.alibaba.druid.support.json.JSONUtils;
import com.boot.entity.SysOperLog;
import com.boot.aop.annotation.ApiLog;
import com.boot.service.ISysOperLogService;
import com.boot.utils.WebUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Collection;
import java.util.Map;

/**
 * 操作日志记录处理
 *
 * @author mkq
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    @Resource
    ISysOperLogService sysOperLogService;

    @Pointcut("@annotation(com.boot.aop.annotation.ApiLog)")
    public void myPoincut() {
    }


    @Around("@annotation(apiLog)")
    public Object around(ProceedingJoinPoint point, ApiLog apiLog) throws Throwable {
        Object result = null;
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(point.getArgs()));
//        long beginTime = System.currentTimeMillis();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        result = point.proceed();
        stopWatch.stop();
        long time = stopWatch.getTotalTimeMillis();
//        long time = System.currentTimeMillis() - beginTime;
        HttpServletRequest request = WebUtil.getRequest();
        // 类名
        String className = point.getTarget().getClass().getName();
        // 方法名
        String methodName = point.getSignature().getName();

        SysOperLog log = new SysOperLog();
        log.setModuleType(apiLog.moduleType());
        log.setLogType(apiLog.logTypeEnum().getLogName());
        // 方法中文名称
        log.setMethodName(apiLog.methodName());
        // 方法名
        log.setMethod(className + "." + methodName + "()");
        // 所在类
        log.setMethodClass(className);
        //  方法执行时间
        log.setRespTime(time);
        // 请求ip
        log.setOperIp(WebUtil.getIP(request));
        // 请求Url
        log.setOperUrl(new URI(request.getRequestURI()).getPath());
        // 获取请求参数
        setRequestValue(point, log);
        // 执行结果：返回值
        log.setJsonResult(String.valueOf(result));

        sysOperLogService.save(log);
        return result;
    }

//    /**
//     * 处理完请求后执行
//     *
//     * @param joinPoint 切点
//     */
//    @AfterReturning(pointcut = "@annotation(apiLog)", returning = "jsonResult")
//    public void doAfterReturning(JoinPoint joinPoint, ApiLog apiLog, Object jsonResult) throws Exception {
//        handleLog(joinPoint, apiLog, null, jsonResult);
//    }

    @AfterThrowing(value = "@annotation(apiLog)", throwing = "e")//响应myPoincut方法的口号
    public void myAfterThrowing(JoinPoint joinPoint, ApiLog apiLog, Exception e) throws Exception {//e是目标方法的真实发生异常后抛出的异常对象。
        handleLog(joinPoint, apiLog, e, null);
    }

    private void handleLog(final JoinPoint joinPoint, ApiLog apiLog, final Exception e, Object jsonResult) throws Exception {

        // 获得ApiLog注解
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
//        ApiLog apiLog = method.getAnnotation(ApiLog.class);
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        SysOperLog log = new SysOperLog();
        log.setModuleType(apiLog.moduleType());
        log.setLogType(apiLog.logTypeEnum().getLogName());
        log.setMethodName(apiLog.methodName());
        log.setMethodName(methodName);
        log.setMethodClass(className);

        HttpServletRequest request = WebUtil.getRequest();

        log.setOperIp(WebUtil.getIP(request));
        log.setOperUrl(new URI(request.getRequestURI()).getPath());
        log.setMethod(request.getMethod());
        String msg = getExceptionAllinformation(e);
        log.setRemark(msg.length() > 2000 ? msg.substring(0, 2000) : msg);

        // 获取请求参数
        setRequestValue(joinPoint, log);
        sysOperLogService.save(log);
    }

    public static String getExceptionAllinformation(Exception ex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e) {
        }
        return ret;
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception {
        String requestMethod = operLog.getRequestMethod();
//        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
//            String params = argsArrayToString(joinPoint.getArgs());
//            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
//        } else {
//            // 获取路径参数
//            Map<?, ?> paramsMap = (Map<?, ?>) WebUtil.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
//            operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
//        }
        // 获取路径参数
        Map<?, ?> paramsMap = (Map<?, ?>) WebUtil.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        String params = argsArrayToString(joinPoint.getArgs());
        operLog.setOperParam(StringUtils.substring(params, 0, 2000));
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(joinPoint.getArgs()));
        HttpServletRequest request = WebUtil.getRequest();
        Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.forEach((k, v) -> {
            // 这里可以处理参数，例如打印
            System.out.println(k + "=" + v[0]);
        });
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (ObjectUtils.isNotEmpty(o) && !isFilterObject(o)) {
                    try {
                        Object jsonObj = JSONUtils.toJSONString(o);
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }

}
